<script lang="ts" setup>
import html2canvas from 'html2canvas';
import { concat, filter, find, isEmpty, map, trim } from 'lodash';
import { v4 } from 'uuid';
import { ref } from 'vue';
import { post } from '../../axios/index';
import EchartsThree from './echarts-three.vue';

const textarea = ref('');
const answer = ref();
const loading = ref(false);
const captureRef = ref();
const defaultKeyValue = { key: 'Enter' };

const captureHandler = () => {
  loading.value = true;
  html2canvas(captureRef.value, {
    allowTaint: false,
    useCORS: true,
  }).then(canvas => {
    const screenshotUrl = canvas.toDataURL('image/png');

    askHandler(
      defaultKeyValue,
      {
        model: "kimi",
        messages: [
          {
            role: "user",
            content: [
              {
                type: "image_url",
                image_url: {
                  url: "https://img.picgo.net/2024/06/10/-131dcb6599a293f2b.png" ?? screenshotUrl
                }
              },
              {
                type: "text",
                text: "图像描述了什么？"
              }
            ]
          }
        ],
        use_search: false,
        link: screenshotUrl,
        desc: '图像描述了什么？'
      }
    )
    // const imgUrl = canvas.toDataURL('image/png')
    // const a = document.createElement('a')
    // a.href = imgUrl
    // a.setAttribute('download', '图片.png')
    // a.click()
  }).catch(() => {
    loading.value = false;
  })
};

const askHandler = (e: any, params?: any) => {
  if ((trim(textarea.value)?.length>0 || !isEmpty(params)) && e.key === defaultKeyValue.key) {
    loading.value = true;
    post(
      '/v1/chat/completions',
      params ?? {
        model: "kimi",
        messages: [
          {
            role: "user",
            content: textarea.value
          }
        ],
        use_search: true,
        stream: false
      },
      {
        baseURL: 'http://localhost:8000',
        url: '',
        headers: {
          Authorization: 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyLWNlbnRlciIsImV4cCI6MTcyNTU1MDk1MiwiaWF0IjoxNzE3Nzc0OTUyLCJqdGkiOiJjcGhpa3E2NzY4ajVhNGltaWRjZyIsInR5cCI6InJlZnJlc2giLCJzdWIiOiJjcGZibTFsdmJmNnRwNGtlMzRkZyIsInNwYWNlX2lkIjoiY3BmYm0xbHZiZjZ0cDRrZTM0ZDAiLCJhYnN0cmFjdF91c2VyX2lkIjoiY3BmYm0xbHZiZjZ0cDRrZTM0Y2cifQ.Wt-FmMKclI5N0H4qOtLohCwlZ5YNflZImvpgdROhKzhH600nrpKCie8BO3Tn5cRiirCQ16YcEhktyUJlf7laQg'
        },
      }
    ).then(res => {
      answer.value = concat(
        map(
          res.data?.choices,
          i => ({ ...i?.message, uuid: v4(), ask: textarea.value, image: { link: params?.link, desc: params?.desc } })
        ),
        answer.value ?? []
      );
      loading.value = false;
    }).catch(() => {
      loading.value = false;
    });
  }
  if ((trim(textarea.value)?.length === 0 && isEmpty(params)) && e.key === defaultKeyValue.key) {
    textarea.value = '';
  }
};

const deleteHander = (uuid: string) => {
  answer.value = filter(answer.value, i => i.uuid !== uuid);
};

</script>

<template>
  <el-row :gutter="20" class="kimi_style">
    <el-col :span="12" class="part">
      <el-button class="ask-btn" type="primary" @click="captureHandler()">图中的内容</el-button>
      <div class="capture-cantainer" ref="captureRef">
        <EchartsThree :showPhoenix="Boolean(find(answer, i => i?.ask?.indexOf('凤凰') >= 0))" />
      </div>
    </el-col>
    <el-col :span="12" class="part">
      <el-card class="kimi-container">
        <div class="answer">
          <el-skeleton v-if="loading" :rows="5" animated />
          <el-empty v-else-if="isEmpty(answer)" description="&nbsp;" />
          <p class="answer-content" v-else v-for="i in (answer ?? [])" :key="i.uuid">
            <el-space direction="vertical">
              <el-alert type="info" close-text="删除会话" @close="deleteHander(i.uuid)">
                <span v-if="i.ask" v-html="i.ask"></span>
                <el-space v-else direction="vertical">
                  <el-tag type="primary">{{ i.image.desc }}</el-tag>
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="i.image.link"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="[i.image.link]"
                    :initial-index="1"
                    fit="cover"
                  />
                </el-space>
              </el-alert>
              <el-alert type="success" close-text="重新生成" @close="askHandler(defaultKeyValue)">
                <span v-html="i.content"></span>
              </el-alert>
            </el-space>
          </p>
        </div>
        <el-input
          clearable
          v-model="textarea"
          :disabled="loading"
          placeholder="请输入。。。"
          @keydown="askHandler"
        />
      </el-card>
    </el-col>
  </el-row>
</template>

<style lang='less' src='./style.less' scoped />